<template>
    <div class="chatPage">
        <div class="chatTop">
            <i class="iconfont icon-xiangzuojiantou" @click="back"></i>
            <p>{{$route.query.nickname}}</p>
            
            <div>
                <van-popover
                    v-model="showPopover"
                    trigger="click"
                    
                    placement="bottom-end"
                >   
                    <div class="list">
                        <ul>
                            <li @click="follow($route.params.toUserId)">{{isFollow === true ? '已关注' : '关注'}}</li>
                            <li @click="report">举报</li>
                        </ul>
                    </div>
                    <template #reference>
                        <van-button type="primary">. . .</van-button>
                    </template>
                </van-popover>
            </div>
        </div>
        <div class="chatCenter">
            <div v-for="(chat,index) in chatRrecord" :key="index" :class="chat.fromUser == decode.userId ? 'right' : 'left'">
                <router-link :to="`/themself/${chat.fromUser == decode.userId ? chat.fromUser : chat.toUser}`">
                    <van-image 
                        width="1rem" 
                        height="1rem" 
                        radius="100%" 
                        fit="cover" 
                        :src="chat.fromUser == decode.userId ? fromUserAvatar : toUserAvatar" 
                    />
                </router-link>
                <p>{{chat.content}}</p>
            </div>
            <!-- <p class="time" v-for="(chat,index) in chatRrecord" :key="index" v-if="index===0 || index%10===0">{{chat.sendTime}}</p> -->
            <!-- <div class="left">
                <van-image 
                    width="1rem" 
                    height="1rem" 
                    radius="100%" 
                    fit="cover" 
                    src="https://img.yzcdn.cn/vant/cat.jpeg" 
                />
                <p>消息</p>
            </div>
            <p class="time">时间</p>
            <div class="right">
                <van-image 
                    width="1rem" 
                    height="1rem" 
                    radius="100%" 
                    fit="cover" 
                    src="https://img.yzcdn.cn/vant/cat.jpeg" 
                />
                <p>消息内容</p>
            </div> -->
        </div>
        <div class="chatFoot">
            <input type="text" placeholder="请友善发言！" @keydown.enter="sendOut" v-model="value"/>
            <button @click="sendOut">发 送</button>
        </div>
        <van-dialog v-model="showReport" title="举报" show-cancel-button :before-close="onBeforeClose">
            <van-radio-group v-model="checked">
                <van-cell-group inset>
                    <van-cell v-for="(msg,index) in messageList" :key="index" :title="msg" clickable @click="checked = index">
                        <template #right-icon>
                            <van-radio :name="index"/>
                        </template>
                    </van-cell>
                </van-cell-group>
            </van-radio-group>
        </van-dialog>
    </div>
</template>

<script>
import { Toast } from 'vant';
import jwtDecode from 'jwt-decode'
import axios from 'axios'
export default {
    name:'ChatPage',
    data() {
        return {
            show:false,
            showPopover: false,
            showReport:false,
            messageList:['血腥暴力','恶意伤人','煽风点火','信息虚假','色情低俗','涉嫌抄袭',],
            checked:0,
            value:'',
            decode:null,
            isFollow:false,
            chatRrecord:null,
            fromUserAvatar:null,//自己的头像
            toUserAvatar:null
        }
    },
    updated(){
        let ele = document.getElementsByClassName('chatCenter')[0];
        ele.scrollTop = ele.scrollHeight;
    },
    mounted() {
        let token=sessionStorage.getItem("token")
        this.decode = jwtDecode(token);
        let that = this
        //连接之后接口服务器消息
        this.global.ws.onmessage = function(msg){
            let aa = JSON.parse(msg.data)
            this.chatRrecord.push({
                content:aa.content,
                fromUser:aa.fromUserId
            })
            console.log(msg.data)
        }
        //检查是否关注了对方
        axios({
            url:'/follow/judgeFollow',
            method:'get',
            params:{
                userId:this.decode.userId,
                useredId:this.$route.params.toUserId
            },
            headers:{
                'Authentication-Token':JSON.parse(sessionStorage.getItem("token"))
            }
        }).then(data=>{
            if(data.data.data === '您未关注此用户'){
                this.isFollow = false
            }else{
                this.isFollow = true
            }
        }).catch(err=>{
            console.log(err)
        })
        //更新聊天框状态
        const initParam = new URLSearchParams()
        initParam.append('fromUser',that.decode.userId)
        initParam.append('toUser',that.$route.params.toUserId)
        axios({
            url:'/chat/inWindows',
            method:'post',
            data:initParam,
            headers:{
                'Authentication-Token':JSON.parse(sessionStorage.getItem("token"))
            }
        }).then(data=>{
            // console.log(data)
            if(data.data.code === 20000){
                console.log('聊天框状态更新')
            }
        }).catch(err=>{
            console.log(err)
        }) 
        async function test(){
            //首先检查两个人是否是第一次聊天
            let first = await axios({
                    url:'/chat/isFirstChat',
                    method:"get", 
                    headers:{
                        'Authentication-Token':JSON.parse(sessionStorage.getItem("token"))
                    },
                    params:{
                        fromUser:that.decode.userId,
                        toUser:that.$route.params.toUserId
                    }
                })
                console.log(first)
            if(first){
                that.fromUserAvatar = first.data.data.fromUserAvatar
                that.toUserAvatar = first.data.data.toUserAvatar
                //查找聊天记录
                axios({
                    url:'/chat/getChatRecords',
                    method:'get',
                    params:{
                        fromUser:that.decode.userId,
                        toUser:that.$route.params.toUserId
                    },
                    headers:{
                        'Authentication-Token':JSON.parse(sessionStorage.getItem("token"))
                    }
                }).then(data=>{
                    // console.log(data)
                    that.chatRrecord = data.data.data
                }).catch(err=>{
                    console.log(err)
                })
            }
        }
        test()
    },
    created() {
        
    },
    methods: {
        //返回上一页
        back(){
            window.history.back(-1);
        },
        follow(userId){
            //这个是关注
            const followParam = new URLSearchParams()
            followParam.append('userId',String(this.decode.userId))//关注人的id
            followParam.append('useredId',String(userId))//被关注人的id
            axios({
                url:'/follow/addFollow',
                method:'post',
                headers:{
                    'Authentication-Token':JSON.parse(sessionStorage.getItem("token"))
                },
                data:followParam
            }).then(data=>{
                if(data.data.data !== '成功关注'){
                    this.cancel(userId)//取消关注
                }else{
                    if(data.data.code === 20000){
                        this.isFollow = true
                        Toast.success('已关注对方');
                        console.log('关注成功')
                        //给服务器发送消息
                        let sendParam = new URLSearchParams()
                        sendParam.append('bodyMessage',this.content)//这里有点问题！！！！！！！！！！！！！
                        sendParam.append('content',`${this.decode.nickname} 关注了你`)
                        sendParam.append('form',String(this.decode.userId))
                        sendParam.append('calsses',String(4))
                        sendParam.append('to',String(this.$route.params.toUserId))
                        sendParam.append('username',this.decode.username)
                        axios({
                            method:'post',
                            url:'/body/sendMessage',
                            data:sendParam,
                            headers:{
                                'Authentication-Token':JSON.parse(sessionStorage.getItem("token"))
                            },
                        }).then(data=>{
                            if(data.data.code === 20000){
                                console.log('发送成功')
                            }
                        }).catch(err=>{
                            console.log(err)
                        })
                    }
                }
            }).catch(err=>{
                console.log(err)
            })
            this.showPopover = false
        },
        report(){
            this.showReport = true
            this.showPopover = false
        },
        //取消关注
        cancel(userId){
            const calcelParam = new URLSearchParams()
            calcelParam.append('userId',String(this.decode.userId))
            calcelParam.append('useredId',String(userId))
            axios({
                url:'/follow/deleteFollow',
                method:"DELETE",
                data:calcelParam,
                headers:{
                    'Authentication-Token':JSON.parse(sessionStorage.getItem("token"))
                }
            }).then(data=>{//取消关注之后
                if(data.data.code === 20000){
                    this.isFollow = false
                    Toast.success('已取消关注');
                    console.log('取消关注')
                }
            }).catch(err=>{
                console.log(err)
            })
        },
        onBeforeClose(e,so){
            if(e === 'confirm'){
                //确认举报
                
                so()//关闭那个弹窗
            }else{
                console.log('点击取消')
                so()

            }
        },
        sendOut(){
            if(this.value){
                this.global.ws.send(JSON.stringify({
                    "linkId": this.$route.query.linkId,
                    "fromUser": this.decode.userId,//自己的id
                    "toUser": this.$route.params.toUserId,//对方的id
                    "content": this.value,//文字内容
                    "type": 1,//消息类型   文字是1 图片是2
                    "nickname": this.decode.nickname,//我的昵称
                    "avatar": this.decode.img//我的头像
                }))
                //发送之后要更新聊天记录的列表
                this.chatRrecord.push({
                    content:this.value,
                    fromUser:this.decode.userId
                })
                //之后让滚动条向上滚
                // document.getElementById("div").scrollHeight
                this.value = ''
            }
        },
        leftMsg(){

        }
    },
}
</script>

<style lang="less" scoped>

    .van-button--primary{
        color:black;
        border: none;
        background-color: white;
        display: inline;
        padding: 0;
        font-size: 0.4rem;
        height: auto;
    }

    .list{
        ul{
            list-style: none;
            li{
                padding: 0.2rem 0rem;
                font-size: 0.35rem;
                text-align: center;
                width: 2.5rem;
                &:nth-child(1){
                    border-bottom: solid 1px #e4e4e4;
                }
            }
        }
    }
    .chatPage{
        display: flex;
        flex-direction: column;
        height: 100vh;
        .chatTop{
            display: flex;
            justify-content: space-between;
            padding: 0.2rem 0.3rem;
            background-color: white;
            p{
                display: flex;
                align-items: center;
                font-size: 0.4rem;
                i{
                    margin-right: 0.2rem;
                }
            }
            >div{
                display: flex;
                >button{
                    padding: 0.1rem 0.3rem;
                    background-color: white;
                    color: var(--themeColor);
                    border: solid 1px;
                    border-color: var(--themeColor);
                    border-radius: 0.4rem;
                    margin-right: 0.2rem;
                }
                >p{
                    font-size: 0.4rem;
                    font-weight: 600;
                }
            }
        }
        .chatCenter{
            background-color: #f5f5f5;
            flex: 1;
            overflow-y: scroll;
            padding: 0 0.3rem;
            .time{
                color: #868686;
                text-align: center;
            }
            div{
                display: flex;
                margin-bottom: 0.4rem;
                p{
                    max-width: 50vw;
                    background-color: white;
                    padding: 0.1rem 0.2rem;
                    font-size: 0.35rem;
                    display: flex;
                    align-items: center;
                    border-radius: 0.2rem;
                }
            }
            .left{
                flex-direction: row;
                p{
                    margin-left: 0.4rem;
                }
            }
            .right{
                flex-direction: row-reverse;
                p{
                    background-color: var(--themeColor);
                    color: white;
                    margin-right: 0.4rem;
                }
            }
        }
        .chatFoot{
            display: flex;
            padding: 0.2rem 0.3rem;
            input{
                flex: 1;
                background-color: #f7f7f7;
                text-indent: 0.2rem;
                outline: none;
                border: none;
                padding: 0.2rem;
                margin-right: 0.3rem;
                font-size: 0.35rem;
            }
            button{
                background-color: var(--themeColor);
                color: white;
                border-radius: 0.4rem;
                padding: 0.2rem 0.3rem;
                outline: none;
                border: none;
            }
        }
    }

    .overlay{
        position: absolute;
        top: 0px;
        left: 0px;
        background-color: rgba(0,0,0,.3);
        width: 100%;
        height: 100%;
        overflow: hidden;
        z-index: 99;
        .content{
            background-color: white;
            position: absolute;
            bottom: 0%;
            width: 100%;
            height: auto;
            color: black;
            font-size: 0.4rem;
            .contentTop{
                padding: 0.3rem;
                padding-bottom: 0;
                display: flex;
                justify-content: space-between;
                p{
                    text-align: center;
                    padding: 0.1rem 0rem;
                    &:nth-child(3){
                        color: var(--themeColor);
                        font-size: 0.35rem;
                    }
                }
                
            }
            .mainContent{
                padding: 1rem 0.3rem;
                display: flex;
                input{
                    flex: 1;
                    font-size: 0.35rem;
                    background-color: #f3f3f3;
                    padding: 0.3rem;
                    outline: none;
                    border: none;
                    border-radius: 0.3rem;
                }
            }
        }
    }

    .slid-enter-active{
        animation: slidAnimate 0.5s;
        animation-fill-mode : forwards ;
    }
    .slid-leave-active{
        animation: slidAnimate reverse 0.5s forwards;
    }

    @keyframes slidAnimate {
        from{
            bottom: -50%;
        }to{
            bottom: 0%;
        }
    }
</style>